package com.yunshang.ysmall.controller;


import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.richerpay.utils.HttpClientUtils;
import com.richerpay.utils.SignatureUtil;
import com.yunshang.ysmall.model.CodePayModel;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.util.DateUtils;


@Controller
@RequestMapping("/weChat")
public class WeChatController { 
	
	private static String REQUEST_URL = "https://openapi.qfpay.com";

	private static String QF_KEY = "A59FC941F3DB46F3B20379C924B4FB25";

	private static String QF_CODE = "FAEF5D1CA0D54BDBA972298A222E1476";
	
	
private static Logger logger = LoggerFactory.getLogger(WeChatController.class);

	@RequestMapping("weChatTest")
	public String weChatTest(HttpServletRequest request,Model model,HttpServletResponse response ){
		Map<String, String> map = new HashMap<String, String>();
		map.put("app_code",QF_CODE);
		map.put("redirect_uri","http://www.houheshangpin.com/weChat/weChatPay");
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		return "redirect:"+REQUEST_URL+"/tool/v1/get_weixin_oauth_code?app_code="+QF_CODE+
				"&redirect_uri="+map.get("redirect_uri")+"&sign="+sign;
	}
	
	
	//{"resperr": "", "respcd": "0000", "respmsg": "", "openid": "oo3Lss5Yr3vmpoPo8ZZsGQlGFFAI"}"
	//回调的code
	@RequestMapping("weChatPay")
	public String weChatPay(HttpServletRequest request,HttpServletResponse response){
	System.out.println("获取金额"+((OrderInfo)request.getSession().getAttribute("orderInfo")).getTransAmt()+"获取积分："+((OrderInfo)request.getSession().getAttribute("orderInfo")).getTransBonus());
		logger.info("[code]:"+request.getParameter("code"));
		String appId=null;
		String timeStamp=null;
		String nonceStr=null;
		String packages=null;
		String signType=null;
		String paySign=null;
		String url=null;
		try {
		//接收第三方平台的code
		String code=request.getParameter("code");
		Map<String, String> map = new HashMap<String, String>();
		map.put("code",code);
		map.put("mchid", "dWamPhlnpW");
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		String result=HttpClientUtils.httpGetForQf(REQUEST_URL+"/tool/v1/get_weixin_openid?code="+code+"&mchid=dWamPhlnpW",QF_CODE,sign);
		JSONObject jsonObject=JSONObject.parseObject(result);
		System.out.println(result);
		if(jsonObject.getString("respcd").equals("0000")){
			//获取oppenid
			String  openid=jsonObject.getString("openid");
			//调用支付接口
			CodePayModel codePayModel=new CodePayModel();
			codePayModel.setGoodsName("厚合支付商品");
			codePayModel.setMerchantOrderId(((OrderInfo)request.getSession().getAttribute("orderInfo")).getOrderId());
			System.out.println("获取订单的id："+((OrderInfo)request.getSession().getAttribute("orderInfo")).getOrderId());
			codePayModel.setTradeAmount(((OrderInfo)request.getSession().getAttribute("orderInfo")).getTransAmt());
			codePayModel.setOpenId(openid);
			String resultPay=unifiedOrder(codePayModel);
			JSONObject jsonObj=JSONObject.parseObject(resultPay);
			//获取调用微信h5支付的接口
			appId=jsonObj.getJSONObject("pay_params").getString("appId");
			timeStamp=jsonObj.getJSONObject("pay_params").getString("timeStamp");
			nonceStr=jsonObj.getJSONObject("pay_params").getString("nonceStr");
			packages=jsonObj.getJSONObject("pay_params").getString("package");
			signType=jsonObj.getJSONObject("pay_params").getString("signType");
			paySign=jsonObj.getJSONObject("pay_params").getString("paySign");
			//调用支付接口
			url="https://o2.qfpay.com/q/direct?mchntnm="+URLEncoder.encode("邦呈有限公司","utf-8")+"&txamt=100&goods_name="
					+URLEncoder.encode("厚合微信支付","utf-8")+"&redirect_url=http://www.houheshangpin.com/weChat/weChatSuccess&package="+packages
					+"&timeStamp="+timeStamp+"&signType="+signType+"&paySign="+paySign+"&appId="+appId+"&nonceStr="+nonceStr ;
			//清空session中的值
			request.getSession().getAttribute("orderInfo");
		}else{
			logger.info("[errorInformation:]"+jsonObject.getString("respcd") +"[errorDiscription:]"+jsonObject.getString("resperr"));
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:"+url;
	}
	
	
	@RequestMapping("weChatSuccess")
	public String weChatSuccess(){
		return "redirect:http://www.houheshangpin.com/member/main";
	}
	
	//支付接口
	public String unifiedOrder(CodePayModel codePayModel)
			throws Exception {
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("txdtm",DateUtils.currentDate("yyyy-MM-dd HH:mm:ss"));//请求的交易时间
		map.put("goods_name", codePayModel.getGoodsName());//商品的名称和标示
		map.put("out_trade_no", codePayModel.getMerchantOrderId());//订单id
		map.put("mchid", "dWamPhlnpW");//子商户号
		map.put("pay_type", "800207");//微信公众号支付
		map.put("sub_openid", codePayModel.getOpenId());//微信公众号的id

		map.put("txcurrcd","CNY");//设置请求的币种
		map.put("txamt", codePayModel.getTradeAmount().movePointRight(2)
				.toString()); // 单位分
			//将参数进行加密
		String md5Str = SignatureUtil.createLinkString(map)+QF_KEY;
		//设置签名
		String sign = SignatureUtil.md5Encrypt(md5Str);
		//返回该线程的标识符
		logger.info("[" + Thread.currentThread().getId()
				+ "][send to qianfang]:" + JSONObject.toJSONString(map));
		//发送请求到钱方  REQUEST_URL+"/trade/v1/payment" 。第一个参数是发送的地址。第二个参数是传入的参数 。第三个是钱方的code 。第四个是钱方参数的签名
		String result = HttpClientUtils.httpPostForQfpay(REQUEST_URL+"/trade/v1/payment", map, QF_CODE, sign);
		return result;
	}
}
